package com.lu.spzx.manager.service.impl;

import com.lu.spzx.manager.helper.MenuHelper;
import com.lu.spzx.manager.mapper.SysMenuMapper;
import com.lu.spzx.manager.service.SysMenuService;
import com.lu.spzx.model.entity.system.SysMenu;
import com.lu.spzx.model.entity.system.SysUser;
import com.lu.spzx.model.vo.common.ResultCodeEnum;
import com.lu.spzx.model.vo.system.SysMenuVo;
import com.lu.spzx.service.exception.GuiguException;
import com.lu.spzx.utils.AuthContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> findNodes() {
        List<SysMenu> sysMenuList = this.sysMenuMapper.selectAll();
        if (CollectionUtils.isEmpty(sysMenuList)) return null;

        // 构建树形菜单
        List<SysMenu> treeList = MenuHelper.buildTree(sysMenuList);
        return treeList;
    }

    @Override
    public void save(SysMenu sysMenu) {
        this.sysMenuMapper.insert(sysMenu);
    }

    @Override
    public void updateById(SysMenu sysMenu) {
        this.sysMenuMapper.updateById(sysMenu);
    }

    @Override
    public void removeById(Long id) {
        // 先查询是否存在子菜单,如果存在不允许进行删除
        int count = this.sysMenuMapper.countByParentId(id);
        if (count > 0) {
            throw new GuiguException(ResultCodeEnum.NODE_ERROR);
        }

        // 不存在子菜单直接删除
        this.sysMenuMapper.deleteById(id);
    }

    @Override
    public List<SysMenuVo> findUserMenuList() {
        // 获取当前登录用户的 id
        SysUser sysUser = AuthContextUtil.get();
        Long userId = sysUser.getId();

        List<SysMenu> sysMenuList = this.sysMenuMapper.selectListByUserId(userId);

        // 构建树形数据
        List<SysMenu> sysMenuTreeList = MenuHelper.buildTree(sysMenuList);
        return this.buildMenus(sysMenuTreeList);
    }

    // 将List<SysMenu>对象转换成List<SysMenuVo>对象
    private List<SysMenuVo> buildMenus(List<SysMenu> menus) {
        List<SysMenuVo> sysMenuVoList = new LinkedList<>();

        for (SysMenu sysMenu : menus) {
            SysMenuVo sysMenuVo = new SysMenuVo();
            sysMenuVo.setTitle(sysMenu.getTitle());
            sysMenuVo.setName(sysMenu.getComponent());

            List<SysMenu> children = sysMenu.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                sysMenuVo.setChildren(buildMenus(children));
            }
            sysMenuVoList.add(sysMenuVo);
        }

        return sysMenuVoList;
    }

}